package com.teama4.shop.controller;

import com.teama4.shop.annotation.NeedLogin;
import com.teama4.shop.domain.Cart;
import com.teama4.shop.domain.CartExample;
import com.teama4.shop.domain.Specification;
import com.teama4.shop.domain.SpecificationExample;
import com.teama4.shop.mapper.ViewHistoryMapper;
import com.teama4.shop.service.CartService;
import com.teama4.shop.service.SpecificationService;
import com.teama4.shop.utils.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private SpecificationService specificationService;
    @NeedLogin
    @RequestMapping("comodityCountChange")
    public void comodityCountChange(HttpServletRequest req, HttpServletResponse resp, Integer cartId, Integer count) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Cart cart = new Cart();
            cart.setId(cartId);
            cart.setCommodityCount(count);
            int insResult = cartService.updateByPrimaryKeySelective(cart) ;
            if (insResult > 0) {
                //如果插入成功
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "ok");
                JSONUtil.printByJSON(resp, map);
            } else {
                //如果插入失败
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "fail");
                JSONUtil.printByJSON(resp, map);
            }

        } else {
            //如果session获取不到值
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "noSession");
            JSONUtil.printByJSON(resp, map);
        }
    }



    /**
     * 添加商品到购物车
     *
     * @param commodityId     商品id
     * @param specificationId 商品规格id <0为空
     * @param commodityCount  商品数量 <0为空
     */
    @NeedLogin
    @RequestMapping("addToCart")
    public void addToCart(HttpServletRequest req, HttpServletResponse resp, Integer commodityId, Integer specificationId, Integer commodityCount) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer userId = (Integer) session.getAttribute("userId");
            if (commodityCount <0 || commodityCount == 0) {
                commodityCount=1;
            }
            if(specificationId<0){
                SpecificationExample specificationExample = new SpecificationExample();
                specificationExample.createCriteria().andCommodityIdEqualTo(commodityId);
                specificationId = specificationService.selectByExample(specificationExample).get(0).getId();

            }

            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andCommodityIdEqualTo(commodityId);
            criteria.andUserIdEqualTo(userId);
            criteria.andSpecificationIdEqualTo(specificationId);
            List<Cart> carts = cartService.selectByExample(cartExample);
            //如果数据库中没有此条记录
            if (carts.size() <= 0) {
                Cart ca = new Cart();
                ca.setCommodityId(commodityId);
                ca.setUserId(userId);
                ca.setSpecificationId(specificationId);
                ca.setCommodityCount(commodityCount);
                int insResult = cartService.insertSelective(ca) ;
                if (insResult > 0) {
                    session.setAttribute("cartAllCount",( Integer) session.getAttribute("cartAllCount")+commodityCount);
                    //如果插入成功
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "ok");
                    JSONUtil.printByJSON(resp, map);
                } else {
                    //如果插入失败
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "fail");
                    JSONUtil.printByJSON(resp, map);
                }
            } else {
                if (carts != null) {
                    Cart cart = new Cart();
                    cart.setId(carts.get(0).getId());
                    cart.setCommodityCount(carts.get(0).getCommodityCount() + commodityCount);
                    int i = cartService.updateByPrimaryKeySelective(cart);
                    if (i > 0) {
                        session.setAttribute("cartAllCount",( Integer) session.getAttribute("cartAllCount")+commodityCount);

                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("result", "exit");
                        map.put("addCount",commodityCount);
                        JSONUtil.printByJSON(resp, map);
                    } else {
                        //如果插入失败
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("result", "fail");
                        JSONUtil.printByJSON(resp, map);
                    }
                } else {
                    //如果插入失败
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "fail");
                    JSONUtil.printByJSON(resp, map);
                }


            }
        } else {
            //如果session获取不到值
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "noSession");
            JSONUtil.printByJSON(resp, map);
        }
    }

    /**
     * 删除购物车一条记录
     *
     * @param cartId 购物车id
     */
    @NeedLogin
    @RequestMapping("delCart")
    public void delCart(HttpServletRequest req, HttpServletResponse resp, Integer cartId) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            Cart cart = cartService.selectByPrimaryKey(cartId);
            Integer commodityCount = cart.getCommodityCount();
            session.setAttribute("cartAllCount",( Integer) session.getAttribute("cartAllCount")-commodityCount);
            int res = cartService.deleteByPrimaryKey(cartId);
            if (res > 0) {
                //如果删除成功
                CartExample cartExample = new CartExample();
                cartExample.createCriteria().andUserIdEqualTo((Integer) session.getAttribute("userId"));



                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "ok");
                map.put("count",cartService.selectByExample(cartExample).size());
                JSONUtil.printByJSON(resp, map);
            } else {
                //如果删除失败
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "fail");
                JSONUtil.printByJSON(resp, map);
            }
        } else {
            //如果session获取不到值
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "noSession");
            JSONUtil.printByJSON(resp, map);
        }
    }

    /**
     * 删除多条记录
     *
     * @param req
     * @param resp
     * @param allCheckId
     * @throws UnsupportedEncodingException
     */
    @NeedLogin
    @RequestMapping("/delCheckedCart")
    public void delCheckedCart(HttpServletRequest req, HttpServletResponse resp, String allCheckId) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if (allCheckId != null && allCheckId != "") {
            String[] allCheckIds = allCheckId.split(",");

            HttpSession session = req.getSession(false);
            if (session != null) {
                CartExample cartExample = new CartExample();
                CartExample.Criteria criteria = cartExample.createCriteria();
                List<Integer> allCheckIdsList = new ArrayList<>();

                for (int i = 0; i < allCheckIds.length; i++) {
                    allCheckIdsList.add(Integer.valueOf(allCheckIds[i]));
                }
                criteria.andIdIn(allCheckIdsList);

                Integer commodityCount=0;
                List<Cart> carts = cartService.selectByExample(cartExample);
                for(Cart c : carts){
                    commodityCount+=c.getCommodityCount();
                }
                session.setAttribute("cartAllCount",( Integer) session.getAttribute("cartAllCount")-commodityCount);
                int res = cartService.deleteByExample(cartExample);
                if (res > 0) {
                    //如果删除成功
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "ok");
                    JSONUtil.printByJSON(resp, map);
                } else {
                    //如果删除失败
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "fail");
                    JSONUtil.printByJSON(resp, map);
                }
            } else {
                //如果session获取不到值
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "noSession");
                JSONUtil.printByJSON(resp, map);
            }
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "isNull");
            JSONUtil.printByJSON(resp, map);
        }
    }

    /**
     * 多选添加
     * @param allCheckId 所选id
     * @param idType    1：商品规格id，2：商品id
     */
    @NeedLogin
    @RequestMapping("/addCheckedCart")
    public void addCheckedCart(HttpServletRequest req, HttpServletResponse resp, String allCheckId,int idType) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if (allCheckId != null && allCheckId != "") {
            HttpSession session = req.getSession(false);

            if (session != null && session.getAttribute("userId") != null) {

                String[] allCheckIds = allCheckId.split(",");
                Integer userId = (Integer) session.getAttribute("userId");
                boolean isinsertOk = true;

                boolean isHave =false;


                int errors = 0;
                int haves = 0;
                for (int i = 0; i < allCheckIds.length; i++) {
                    //从获取的specificationId中获取commodityId
                    Integer specificationId =null;
                    Integer commodityId = null;
                    List<Cart> carts = new ArrayList<>();
                    if(idType == 1){
                        //如果是商品类别id
                        specificationId = Integer.valueOf(allCheckIds[i]);
                        Specification specification = specificationService.selectByPrimaryKey(specificationId);
                        commodityId = specification.getCommodityId();

                        //查找Cart中有没有此数据
                        CartExample cartExample = new CartExample();
                        CartExample.Criteria criteria = cartExample.createCriteria();
                        criteria.andUserIdEqualTo(userId);
                        criteria.andSpecificationIdEqualTo(specificationId);
                        criteria.andCommodityIdEqualTo(commodityId);
                        carts = cartService.selectByExample(cartExample);
                    }else if(idType==2){
                        //如果是商品id
                        //specificationId默认为第一个
                        commodityId = Integer.valueOf(allCheckIds[i]);
                        SpecificationExample specificationExample = new SpecificationExample();
                        specificationExample.createCriteria().andCommodityIdEqualTo(commodityId);
                        specificationId = specificationService.selectByExample(specificationExample).get(0).getId();
                    }


                    Integer commodityCount=0;
                        if (carts.size() <= 0) {
                        //将数据插入Cart
                        Cart cart = new Cart();
                        cart.setUserId(userId);
                        cart.setSpecificationId(specificationId);
                        cart.setCommodityId(commodityId);
                        cart.setCommodityCount(1);
                        int res = cartService.insertSelective(cart);
                        if (res <= 0) {
                            commodityCount+=1;
                            isinsertOk=false;
                           errors++;
                        }
                    } else {
                        isHave=true;
                        haves++;
                        if (carts.size() > 0){
                            Integer oneCartId = carts.get(0).getId();
                            Integer oneCartCount = carts.get(0).getCommodityCount();
                            Cart cart = new Cart();
                            cart.setId(oneCartId);
                            cart.setCommodityCount(oneCartCount+1);
                            cartService.updateByPrimaryKeySelective(cart);

                        }

                    }


                    session.setAttribute("cartAllCount",( Integer) session.getAttribute("cartAllCount")+commodityCount);
                }
                //如果每个插入成功并且原来数据库没有
                if (isinsertOk&&!isHave) {
                    //如果成功
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "ok");
                    JSONUtil.printByJSON(resp, map);
                } else if(!isinsertOk) {
                    //如果插入失败
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "fail");
                    map.put("all",allCheckIds.length);
                    map.put("errors",errors);
                    JSONUtil.printByJSON(resp, map);
                }else if(isHave){
                    //如果存在
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("result", "exit");
                    map.put("all",allCheckIds.length);
                    map.put("haves",haves);
                    JSONUtil.printByJSON(resp, map);
                }
            } else {
                //如果session获取不到值
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "noSession");
                JSONUtil.printByJSON(resp, map);
            }
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "isNull");
            JSONUtil.printByJSON(resp, map);
        }
    }



}
